package com.strive.oauth.service.impl;

import com.strive.common.constant.SecurityConstants;
import com.strive.common.feign.UserService;
import com.strive.common.model.LoginAppUser;
import com.strive.common.model.base.Result;
import com.strive.oauth.service.StriveUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @description:
 * @author: bingcun.chen
 * @Date: 2022/3/3 15:36
 * @Version 1.0
 */
@Slf4j
@Service
public class StriveUserDetailsServiceImpl implements StriveUserDetailsService {
    private static final String ACCOUNT_TYPE = SecurityConstants.DEF_ACCOUNT_TYPE;

    @Resource
    private UserService userService;

    @Override
    public boolean supports(String accountType) {
        return ACCOUNT_TYPE.equals(accountType);
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        Result<LoginAppUser> result = userService.findByUsername(username);
        if(result.getStatus() != 200 && Objects.isNull(result.getData())){
            throw new InternalAuthenticationServiceException("用户名或密码错误");
        }
        return checkUser(result.getData());
    }

    @Override
    public SocialUserDetails loadUserByUserId(String openId) {
        Result<LoginAppUser> result = userService.findByOpenId(openId);
        if(result.getStatus() != 200 && Objects.isNull(result.getData())){
            throw new InternalAuthenticationServiceException("openId错误");
        }
        return checkUser(result.getData());
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        Result<LoginAppUser> result = userService.findByMobile(mobile);
        if(result.getStatus() != 200 && Objects.isNull(result.getData())){
            throw new InternalAuthenticationServiceException("mobile错误");
        }
        return checkUser(result.getData());
    }

    private LoginAppUser checkUser(LoginAppUser loginAppUser) {
        if (loginAppUser != null && !loginAppUser.isEnabled()) {
            throw new DisabledException("用户已作废");
        }
        return loginAppUser;
    }
}
